package com.youhome.controller;

import com.github.pagehelper.PageInfo;
import com.youhome.model.ListHubPhoto;
import com.youhome.param.ListHubParam;
import com.youhome.response.ResultPage;
import com.youhome.response.Result;
import com.youhome.response.ResultCode;
import com.youhome.result.*;
import com.youhome.service.ListHubPhotoService;
import com.youhome.service.SolrService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by chen365 on 2018/09/13.
 */
@Api(tags = "房源")
@RestController
@RequestMapping(value = "/houses")
public class HouseController {

    @Value("${oss.domain}")
    private String OSS_DOMAIN;

    @Autowired
    private SolrService solrService;

    @Autowired
    private ListHubPhotoService listHubPhotoService;


    @ApiOperation(value = "房源搜索", notes = "房源搜索", response = ListHubList.class, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "String", name = "action", value = "查询方法(zip,address,city)", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "keyword", value = "查询条件", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "int", name = "page", value = "页码", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "int", name = "pageSize", value = "每页条数,默认20条", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "type", value = "房屋类型", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "int", name = "beds", value = "卧室数量", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "int", name = "baths", value = "卫浴数量", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "int", name = "year", value = "房龄", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "Double", name = "minSize", value = "最小面积", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "Double", name = "maxSize", value = "最大面积", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "Double", name = "minPrice", value = "最小价格", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "Double", name = "maxPrice", value = "最大价格", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "filed", value = "排序字段(bedroomCount：卧室数量;bathroomCount：浴数量;yearBuilt：房龄;livingArea：面积;listPrice:价格)", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "direction", value = "排序方向(asc：升序  desc：降序)", required = false, paramType = "query")
//            @ApiImplicitParam(dataType = "Boolean", name = "isOwn", value = "查询自有房源", required = false, paramType = "query"),
//            @ApiImplicitParam(dataType = "Boolean", name = "isStar", value = "查询明星房源", required = false, paramType = "query"),
//            @ApiImplicitParam(dataType = "Boolean", name = "isShowShareGroup", value = "是否展示分享组名称", required = false, paramType = "query"),
//
//            @ApiImplicitParam(dataType = "Double", name = "minX", value = "minX", required = false, paramType = "query"),
//            @ApiImplicitParam(dataType = "Double", name = "maxX", value = "maxX", required = false, paramType = "query"),
//            @ApiImplicitParam(dataType = "Double", name = "minY", value = "minY", required = false, paramType = "query"),
//            @ApiImplicitParam(dataType = "Double", name = "maxY", value = "maxY", required = false, paramType = "query")

    })
    @GetMapping("/search")
    public Object search(
            @RequestParam(value = "action", defaultValue = "") String action,
            @RequestParam(value = "keyword", defaultValue = "") String keyword,
            @RequestParam(value = "page", defaultValue = "") Integer page,
            @RequestParam(value = "pageSize", defaultValue = "") Integer pageSize,
            @RequestParam(value = "type", defaultValue = "") String type,
            @RequestParam(value = "beds", defaultValue = "") Integer beds,
            @RequestParam(value = "baths", defaultValue = "") Integer baths,
            @RequestParam(value = "year", defaultValue = "") Integer year,
            @RequestParam(value = "minSize", defaultValue = "") Double minSize,
            @RequestParam(value = "maxSize", defaultValue = "") Double maxSize,
            @RequestParam(value = "minPrice", defaultValue = "") Double minPrice,
            @RequestParam(value = "maxPrice", defaultValue = "") Double maxPrice,
            @RequestParam(value = "filed", defaultValue = "") String filed,
            @RequestParam(value = "direction", defaultValue = "asc") String direction
//            @RequestParam(value = "isOwn", defaultValue = "") Boolean isOwn,
//            @RequestParam(value = "isStar", defaultValue = "") Boolean isStar,
//            @RequestParam(value = "isShowShareGroup", defaultValue = "") Boolean isShowShareGroup,
//            @RequestParam(value = "minX", defaultValue = "") Double minX,
//            @RequestParam(value = "maxX", defaultValue = "") Double maxX,
//            @RequestParam(value = "minY", defaultValue = "") Double minY,
//            @RequestParam(value = "maxY", defaultValue = "") Double maxY
    ) {
        try {
            long btime = System.currentTimeMillis();
            if (!StringUtils.isEmpty(action) && !StringUtils.isEmpty(keyword)) {
                if (action.equalsIgnoreCase("zip")) {
                    if (keyword.length() != 5) {
                        return new ResultPage(ResultCode.HOUSE_ILLEGALITY_ZIP_CODE);
                    }
                } else if (action.equalsIgnoreCase("address")) {
                    if (keyword.length() < 3) {
                        return new ResultPage(ResultCode.HOUSE_ADDRESS_LENGTH_SHORTAGE);
                    }
                } else if (action.equalsIgnoreCase("city")) {
                    if (keyword.length() < 3) {
                        return new ResultPage(ResultCode.HOUSE_CITY_LENGTH_SHORTAGE);
                    }
                } else {
                    return new ResultPage(ResultCode.UNSUPPORTED_SEARCH_TYPE);
                }
            }

            String status = "Active";
            Boolean isCheck = null;
            ListHubParam params = null;

            //查询自有房源
            Long companyId = null;
//            if (!StringUtils.isEmpty(isOwn) && isOwn) {
//                BUser currentUser = bUserService.getCurrentUser();
//                if (currentUser != null) {
//                    BCompany bCompany = bCompanyService.selectByUserId(currentUser.getUserId());
//                    if (bCompany == null) {
//                        return new Result(ResultCode.DO_NOT_HAVE_PERMISSION);
//                    }
//                    companyId = bCompany.getCompanyId();
//                    params.setCompanyId(companyId);
//                }
//            }

            if (StringUtils.isEmpty(page) || page < 1) {
                page = 1;
            }

            Double minX = null;
            Double maxX = null;
            Double minY = null;
            Double maxY = null;
            Boolean isStar = null;
            PageInfo<ListHubList> listHubLists = solrService.searchByBean(
                    action, keyword, page, pageSize, type, beds, baths, year,
                    minSize, maxSize, minPrice, maxPrice, filed, direction, isStar,
                    isCheck, minX, maxX, minY, maxY, companyId);


//            if (!StringUtils.isEmpty(isShowShareGroup) && isShowShareGroup) {
//                BUser currentUser = bUserService.getCurrentUser();
//                if (currentUser == null) {
//                    return new ResultPage(ResultCode.EXPIRED_LOGIN);
//                }
//                BCounselor bCounselor = bCounselorService.selectByUserId(currentUser.getUserId());
//                if (bCounselor == null) {
//                    return new ResultPage(ResultCode.DATA_DOES_NOT_EXIST_OR_HAS_BEEN_DELETED);
//                }
//                Long counselorId = bCounselor.getCounselorId();
//                if (!StringUtils.isEmpty(counselorId) && counselorId > 0) {
//                    for (ListHubList listHub : listHubLists.getList()) {
//                        String houseId = listHub.getHouseId();
//                        List<String> shareGroupNames = bShareGroupService.selectShareGroupNameByHouseIdAndCounselorId(counselorId, houseId);
//                        listHub.setShareGroupNames(shareGroupNames);
//                    }
//                }
//            }


            long etime = System.currentTimeMillis();

            System.err.println("执行时间：" + (etime - btime) + "ms");

            return new ResultPage(ResultCode.SUCCESS, listHubLists);

        } catch (Exception e) {
            e.printStackTrace();
            return new ResultPage(ResultCode.FAIL);
        }
    }

    @ApiOperation(value = "搜索联想", notes = "搜索联想", response = AssociateResult.class, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "String", name = "keyword", value = "搜索关键字,三个字符以上", required = true, paramType = "query")
    })
    @GetMapping(value = "/typeahead")
    public Object typeahead(String keyword) {
        System.err.println(keyword);
        if (StringUtils.isEmpty(keyword)) {
            return new Result(ResultCode.EMPTY_PARAMETER);
        }
        if (keyword.length() < 3) {
            return new Result(ResultCode.ERROR_KEYWORD_LENGTH_THREE);
        }
        List<AssociateZip> list_zip = null;
        if (org.apache.commons.lang.StringUtils.isNumeric(keyword)) {
            list_zip = solrService.associateSearchByZip(keyword);
        }

        List<AssociateCity> list_city = null;
        list_city = solrService.associateSearchByCity(keyword);

        List<AssociateAddress> list_address = null;
        list_address = solrService.associateSearchByAddress(keyword);

        AssociateResult associateResult = new AssociateResult();
        associateResult.setAddress(list_address);
        associateResult.setCity(list_city);
        associateResult.setZip(list_zip);

        return new Result(ResultCode.SUCCESS, associateResult);

    }

    @ApiOperation(value = "房源图片", notes = "房源图片", response = String.class, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "String", name = "houseId", value = "房源ID", required = true, paramType = "path")
    })
    @GetMapping(value = "/{houseId}/photos")
    public Object photos(@PathVariable String houseId) {
        System.err.println(houseId);
        if (StringUtils.isEmpty(houseId)) {
            return new Result(ResultCode.EMPTY_PARAMETER);
        }

        ListHubPhoto record = new ListHubPhoto();
        record.setHouseId(houseId);
        record.setIsDownload(true);
        record.setDownloadStatus(1);
        record.setRepeat(false);

        List<ListHubPhoto> list = listHubPhotoService.selectByBean(record);
        List<String> photos = new ArrayList<>();
        for (ListHubPhoto listHubPhoto : list) {
            String ossUrl = listHubPhoto.getOssUrl();
            if (!StringUtils.isEmpty(ossUrl)) {
                ossUrl = OSS_DOMAIN + ossUrl;
                photos.add(ossUrl);
            }
        }
        return new Result(ResultCode.SUCCESS, photos);

    }

}
